import classNames from 'classnames';
import React, { FunctionComponentElement, useContext, useState } from 'react';
import { MenuContext } from './menu';
import { MenuItemProps } from './menuItem';

export interface ISubMenuProps {
  index?: string;
  /**
   * 子菜单的标题
   */
  title: string;
  /**
   * 子菜单的图标
   */
  icon?: string;
  /**
   * 子菜单的子菜单
   */
  children?: React.ReactNode;
  /**
   * 子菜单的样式
   */
  style?: React.CSSProperties;
  /**
   * 子菜单的类名
   */
  className?: string;
}

const SubMenu: React.FC<ISubMenuProps> = ({
  index,
  title,
  children,
  className,
}) => {
  const context = useContext(MenuContext);
  const openedSubMenus = context.defaultOpenSubMenus as Array<string>;
  const isOpened = (index && context.mode === 'vertical') ? openedSubMenus.includes(index) : false;
  const [menuOpen, setOpen] = useState(isOpened);
  const classes = classNames('menu-item submenu-item', className, {
    'is-active': context.index === index,
  });

  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault();
    setOpen(!menuOpen);
  };

  let timer: any;
  const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
    clearTimeout(timer);
    e.preventDefault();
    timer = setTimeout(() => {
      setOpen(toggle);
    }, 300);
  };

  const clickEvents = context.mode === 'vertical' ? {onClick:handleClick}: {};
  const hoverEvents = context.mode !== 'vertical' ? {
    onMouseEnter:(e:React.MouseEvent)=>{ handleMouse(e, true)}, 
    onMouseLeave:(e:React.MouseEvent)=>{ handleMouse(e, false)}, 
  }: {};

  const renderChildren = () => {
    const subMenuClasses = classNames('syx-submenu', {
      'menu-opened': menuOpen,
    });
    const childrenComponent = React.Children.map(children, (child, i) => {
      const childElement = child as FunctionComponentElement<MenuItemProps>;
      // const {index, disabled, className, style, children} = childElement.props;
      const { displayName } = childElement.type;
      if (displayName === 'MenuItem') {
        return React.cloneElement(childElement,{
          index:`${index}-${i}`
        });
      } else {
        Promise.reject('子菜单只能包含MenuItem组件');
      }
    });

    return <ul className={subMenuClasses}>{childrenComponent}</ul>;
  };

  return (
    <li key={index} className={classes} {...hoverEvents}>
      <div className="submenu-title" {...clickEvents}>
        {title}
      </div>
      {renderChildren()}
    </li>
  );
};

SubMenu.displayName = 'SubMenu';

export default SubMenu;
